import { useState, useEffect } from 'react'
import { AuthAPI } from '@/services/api'

interface User {
  id: number
  username: string
  nickname: string
  name: string
  email: string
  mobile: string
  avatar?: string
  sex: number
  status: number
  isLoggedIn: boolean
}

export function useAuth() {
  const [user, setUser] = useState<User | null>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [forceUpdate, setForceUpdate] = useState(0)

  useEffect(() => {
    initializeAuth()
  }, [])

  const initializeAuth = async () => {
    console.log('Initializing auth...') // 调试日志
    
    // 首先检查本地存储的用户信息
    const storedUser = localStorage.getItem('user')
    const token = localStorage.getItem('token')
    
    console.log('Stored user:', storedUser) // 调试日志
    console.log('Stored token:', token) // 调试日志
    
    if (storedUser && token) {
      try {
        const userData = JSON.parse(storedUser)
        console.log('Parsed user data:', userData) // 调试日志
        
        // 先设置本地存储的用户信息
        setUser(userData)
        
        // 然后验证token有效性
        const response = await AuthAPI.getCurrentUser()
        if (response.code === 0 && response.data) {
          const freshUserData: User = {
            ...response.data,
            name: response.data.nickname || response.data.username,
            isLoggedIn: true
          }
          setUser(freshUserData)
          localStorage.setItem('user', JSON.stringify(freshUserData))
        } else {
          // token无效，清除本地存储
          clearAuthData()
        }
      } catch (error) {
        console.error('Failed to get current user:', error)
        // 如果API调用失败，但本地有用户信息，先使用本地信息
        if (storedUser) {
          try {
            const userData = JSON.parse(storedUser)
            setUser(userData)
          } catch (parseError) {
            console.error('Failed to parse stored user:', parseError)
            clearAuthData()
          }
        } else {
          clearAuthData()
        }
      }
    }
    setIsLoading(false)
  }

  const clearAuthData = () => {
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    setUser(null)
  }

  const login = (token: string, userData: any) => {
    console.log('Login called with:', { token, userData }) // 调试日志
    
    // 保存token
    localStorage.setItem('token', token)
    
    // 保存用户信息
    const user: User = {
      id: userData.id,
      username: userData.username,
      nickname: userData.nickname || userData.username,
      name: userData.nickname || userData.username,
      email: userData.email || '',
      mobile: userData.mobile || '',
      avatar: userData.avatar,
      sex: userData.sex || 0,
      status: userData.status || 1,
      isLoggedIn: true
    }
    
    console.log('Setting user:', user) // 调试日志
    setUser(user)
    localStorage.setItem('user', JSON.stringify(user))
    
    // 强制重新渲染
    setForceUpdate(prev => prev + 1)
  }

  const logout = async () => {
    try {
      // 调用后端退出接口
      await AuthAPI.logout()
    } catch (error) {
      console.error('Logout API failed:', error)
    } finally {
      // 无论API调用是否成功，都清除本地数据
      clearAuthData()
    }
  }

  const updateUser = (userData: Partial<User>) => {
    if (user) {
      const updatedUser = { ...user, ...userData }
      setUser(updatedUser)
      localStorage.setItem('user', JSON.stringify(updatedUser))
    }
  }

  return {
    user,
    isLoading,
    isLoggedIn: !!user && user.isLoggedIn,
    login,
    logout,
    updateUser,
    clearAuthData
  }
}
